package com.biz.primus.ms.task.service;

import com.biz.primus.model.task.vo.QuartzTaskVO;
import com.google.common.collect.Lists;
import org.apache.commons.lang.time.DateFormatUtils;
import org.hibernate.service.spi.ServiceException;
import org.quartz.*;
import org.quartz.impl.matchers.GroupMatcher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashSet;
import java.util.List;



/**
 * QuartzTaskService
 * Created by david-liu on 2017/05/22 13:39.
 */
@Service
public class QuartzTaskService {

    private static Logger logger = LoggerFactory.getLogger(QuartzTaskService.class);

    @Autowired
    private Scheduler scheduler;

    public List<QuartzTaskVO> listTasks() {
        List<QuartzTaskVO> list = Lists.newArrayList();

        try {
            for (String groupJob : scheduler.getJobGroupNames()) {
                for (JobKey jobKey : scheduler.getJobKeys(GroupMatcher.groupEquals(groupJob))) {
                    List<? extends Trigger> triggers = scheduler.getTriggersOfJob(jobKey);
                    for (Trigger trigger : triggers) {
                        Trigger.TriggerState triggerState = scheduler.getTriggerState(trigger.getKey());
                        JobDetail jobDetail = scheduler.getJobDetail(jobKey);
                        String cronExpression = "", createTime = "";
                        if (trigger instanceof CronTrigger) {
                            CronTrigger cronTrigger = (CronTrigger) trigger;
                            cronExpression = cronTrigger.getCronExpression();
                            createTime = cronTrigger.getDescription();
                        }
                        QuartzTaskVO info = new QuartzTaskVO();
                        info.setJobName(jobKey.getName());
                        info.setJobGroup(jobKey.getGroup());
                        info.setJobDescription(jobDetail.getDescription());
                        info.setJobStatus(triggerState.name());
                        info.setCronExpression(cronExpression);
                        info.setCreateTime(createTime);
                        list.add(info);
                    }
                }
            }
        } catch (SchedulerException e) {
            e.printStackTrace();
        }

        return list;
    }

    /**
     * 保存定时任务
     */
    @SuppressWarnings("unchecked")
    public void addJob(QuartzTaskVO info, Class<? extends Job> clz) {
        try {
            String jobName = info.getJobName();
            String jobGroup = info.getJobGroup();
            String jobDescription = info.getJobDescription();
            String cronExpression = info.getCronExpression();
            String createTime = DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss");
            if (checkExists(jobName, jobGroup)) {
                logger.info("===> AddJob fail, job already exist, jobGroup:{}, jobName:{}", jobGroup, jobName);
                throw new ServiceException(String.format("Job已经存在, jobName:{%s},jobGroup:{%s}", jobName, jobGroup));
            }
            TriggerKey triggerKey = TriggerKey.triggerKey(jobName, jobGroup);
            JobKey jobKey = JobKey.jobKey(jobName, jobGroup);
            CronScheduleBuilder schedBuilder = CronScheduleBuilder.cronSchedule(cronExpression).withMisfireHandlingInstructionDoNothing();
            CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity(triggerKey).withDescription(createTime).withSchedule(schedBuilder).build();
            JobDetail jobDetail = JobBuilder.newJob(clz).withIdentity(jobKey).withDescription(jobDescription).build();
            scheduler.scheduleJob(jobDetail, trigger);
        } catch (SchedulerException | NullPointerException e) {
            throw new ServiceException("类名不存在或执行表达式错误");
        }
    }

    /**
     * 修改定时任务
     */
    public void edit(QuartzTaskVO info) {
        try {
            String jobName = info.getJobName();
            String jobGroup = info.getJobGroup();
            String jobDescription = info.getJobDescription();
            String cronExpression = info.getCronExpression();
            String createTime = DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss");
            if (!checkExists(jobName, jobGroup)) {
                throw new ServiceException(String.format("Job不存在, jobName:{%s},jobGroup:{%s}", jobName, jobGroup));
            }
            TriggerKey triggerKey = TriggerKey.triggerKey(jobName, jobGroup);
            JobKey jobKey = new JobKey(jobName, jobGroup);
            CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(cronExpression).withMisfireHandlingInstructionDoNothing();
            CronTrigger cronTrigger = TriggerBuilder.newTrigger().withIdentity(triggerKey).withDescription(createTime).withSchedule(cronScheduleBuilder).build();

            JobDetail jobDetail = scheduler.getJobDetail(jobKey);
            jobDetail.getJobBuilder().withDescription(jobDescription);
            HashSet<Trigger> triggerSet = new HashSet<>();
            triggerSet.add(cronTrigger);

            scheduler.scheduleJob(jobDetail, triggerSet, true);
        } catch (SchedulerException e) {
            throw new ServiceException("类名不存在或执行表达式错误");
        }
    }

    public QuartzTaskVO getOne(String jobName, String jobGroup) {
        try {
            TriggerKey triggerKey = TriggerKey.triggerKey(jobName, jobGroup);
            Trigger trigger = scheduler.getTrigger(triggerKey);
            JobKey jobKey = JobKey.jobKey(jobName, jobGroup);
            Trigger.TriggerState triggerState = scheduler.getTriggerState(trigger.getKey());
            JobDetail jobDetail = scheduler.getJobDetail(jobKey);
            String cronExpression = "", createTime = "";
            if (trigger instanceof CronTrigger) {
                CronTrigger cronTrigger = (CronTrigger) trigger;
                cronExpression = cronTrigger.getCronExpression();
                createTime = cronTrigger.getDescription();
            }
            QuartzTaskVO info = new QuartzTaskVO();
            info.setJobName(jobName);
            info.setJobGroup(jobGroup);
            info.setJobDescription(jobDetail.getDescription());
            info.setJobStatus(triggerState.name());
            info.setCronExpression(cronExpression);
            info.setCreateTime(createTime);
            return info;
        } catch (SchedulerException | NullPointerException e1) {
            e1.printStackTrace();
            logger.error(e1.getMessage());
            throw new ServiceException("找不到对应的任务");
        }
    }

    /**
     * 删除定时任务
     */
    public void delete(String jobName, String jobGroup) {
        TriggerKey triggerKey = TriggerKey.triggerKey(jobName, jobGroup);
        try {
            if (checkExists(jobName, jobGroup)) {
                scheduler.pauseTrigger(triggerKey);
                scheduler.unscheduleJob(triggerKey);
                logger.info("===> delete, triggerKey:{}", triggerKey);
            }
        } catch (SchedulerException e) {
            throw new ServiceException(e.getMessage());
        }
    }

    /**
     * 暂停定时任务
     */
    public void pause(String jobName, String jobGroup) {
        TriggerKey triggerKey = TriggerKey.triggerKey(jobName, jobGroup);
        try {
            if (checkExists(jobName, jobGroup)) {
                scheduler.pauseTrigger(triggerKey);
                logger.info("===> Pause success, triggerKey:{}", triggerKey);
            }
        } catch (SchedulerException e) {
            throw new ServiceException(e.getMessage());
        }
    }

    /**
     * 重新开始任务
     */
    public void resume(String jobName, String jobGroup) {
        TriggerKey triggerKey = TriggerKey.triggerKey(jobName, jobGroup);

        try {
            if (checkExists(jobName, jobGroup)) {
                scheduler.resumeTrigger(triggerKey);
                logger.info("===> Resume success, triggerKey:{}", triggerKey);
            }
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
    }

    /**
     * 验证是否存在
     *
     * @throws SchedulerException
     */
    private boolean checkExists(String jobName, String jobGroup) throws SchedulerException {
        TriggerKey triggerKey = TriggerKey.triggerKey(jobName, jobGroup);
        return scheduler.checkExists(triggerKey);
    }
}
